﻿using System;
using System.IO;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows.Forms;

namespace Warl
{
    class PingThread
    {
        private string[,] servers;
        private bool run = false;
        private Main _main;
        private Thread worker;

        public PingThread(Main form)
        {
            this._main = form;
            //
            worker = new Thread(new ParameterizedThreadStart(workerFunction));
        }

        public void recieveUpdate(string[,] servers_)
        {
            if (servers_.Length == 0) { return; }
            Stop();
            //
            servers = servers_;
            //
            Start();
        }

        #region Worker

        private void Start()
        {
            run = true;
            worker.Start();
        }

        private void Stop()
        {
            run = false;
        }

        private void workerFunction(object obj)
        {
            Ping netMon = new Ping();
            //
            while (run)
            {
                int _i = servers.Length / 2;
                for (int i = 0; i < _i;  i++)
                {
                    try
                    {
                        PingReply reply = netMon.Send(servers[i, 1], 120);
                        if (reply.Status == IPStatus.Success)
                            _main.addServer(Convert.ToInt32(servers[i, 0]), null, null, reply.RoundtripTime, false);
                    }
                    catch (PingException) { /*System.Windows.Forms.MessageBox.Show(e.Message); */ _main.addServer(Convert.ToInt32(servers[i, 0]), null, null, 0, false); }
                    //
                    Thread.Sleep(100);
                }
                Thread.Sleep(20000);
            }
        }

        #endregion
    }
}
